package com.adong.tv.ui.presenter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.leanback.widget.Presenter;

import com.adong.tv.R;
import com.adong.tv.model.Movie;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;

/**
 * 电影卡片呈现器
 */
public class MovieCardPresenter extends Presenter {
    
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_movie_card, parent, false);
        return new MovieCardViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, Object item) {
        if (item instanceof Movie) {
            Movie movie = (Movie) item;
            //
            if (viewHolder instanceof MovieCardViewHolder){
                MovieCardViewHolder holder = (MovieCardViewHolder) viewHolder;

                // 设置标题和备注
                holder.titleView.setText(movie.getVodName());
                holder.remarkView.setText(movie.getVodRemarks());

                // 加载图片
                if(movie.getVodPic() != null){
                    Glide.with(holder.imageView.getContext())
                            .load(movie.getVodPic())
                            .apply(new RequestOptions()
                                    .transforms(new CenterCrop(), new RoundedCorners(16))
                                    .placeholder(R.drawable.default_background)
                                    .error(R.drawable.default_background))
                            .into(holder.imageView);
                }

            }
        }
    }
    
    @Override
    public void onUnbindViewHolder(ViewHolder viewHolder) {
        if (viewHolder instanceof MovieCardViewHolder) {
            MovieCardViewHolder holder = (MovieCardViewHolder) viewHolder;
            Glide.with(holder.imageView.getContext()).clear(holder.imageView);
        }
    }
    
    /**
     * 电影卡片视图持有者
     */
    static class MovieCardViewHolder extends ViewHolder {
        private final ImageView imageView;
        private final TextView titleView;
        private final TextView remarkView;
        
        public MovieCardViewHolder(View view) {
            super(view);
            imageView = view.findViewById(R.id.iv_movie_poster);
            titleView = view.findViewById(R.id.tv_movie_title);
            remarkView = view.findViewById(R.id.tv_movie_remark);
        }
    }
} 